package cn.itbox.example.application.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @BelongProject springboot-study
 * @BelongPackage cn.itbox.example.application.config
 * @Description TODO
 * @ClassName ThreadPoolConfig
 * @Author huyanbing
 * @Date 2024/3/12 10:38
 * @Version 1.0.0
 */
@Configuration
public class ThreadPoolConfig {

    public final  static String COMMON_THREAD_POOL_NAME="COMMON_THREAD_POOL_NAME";

    @Bean("threadPoolTaskConfig")
    @ConditionalOnMissingBean
//    @ConfigurationProperties(prefix = "itbox.thread-pool")
    public ThreadPoolTaskConfig threadPoolTaskConfig() {
        return new ThreadPoolTaskConfig();
    }


    /**
     * 异步线程池队列
     *
     * @param threadPoolTaskConfig
     * @return
     */
    @Qualifier(ThreadPoolConfig.COMMON_THREAD_POOL_NAME)
    @Bean(ThreadPoolConfig.COMMON_THREAD_POOL_NAME)
//    @ConditionalOnProperty(
//            prefix = "itbox.thread-pool",
//            name = {"enable"},
//            matchIfMissing = true,
//            havingValue = "true")
    public Executor appTaskExecutor(ThreadPoolTaskConfig threadPoolTaskConfig) {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolTaskConfig.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolTaskConfig.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolTaskConfig.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolTaskConfig.getKeepAliveTime());
        executor.setThreadNamePrefix(threadPoolTaskConfig.getThreadNamePrefix());

        // 线程池对拒绝任务的处理策略
        // CallerRunsPolicy：由调用线程（提交任务的线程）处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();

        // 重点：使用 TTL 提供的 TtlExecutors
        return TtlExecutors.getTtlExecutor(executor);
    }
}
